/*
 * @Author: gonglf
 * @Date: 2022-08-22 15:27:14
 * @LastEditors: gonglf
 * @LastEditTime: 2022-08-22 15:57:40
 * @Description:
 *
 */
package main

import (
	"context"
	"io"
	"log"
	"net"

	"gitee.com/network-learning/rpc/5gRPC_stream/pb"
	"google.golang.org/grpc"
)

type HelloServiceImpl struct{}

func (p *HelloServiceImpl) Hello(ctx context.Context, args *pb.String) (*pb.String, error) {
	reply := &pb.String{Value: "hello:" + args.GetValue()}
	return reply, nil
}

func (p *HelloServiceImpl) Channel(stream pb.HelloService_ChannelServer) error {
	for {
		args, err := stream.Recv() //服务端在循环中接收客户端发来的数据，如果遇到io.EOF表示客户端流被关闭
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}

		reply := &pb.String{Value: "hello:" + args.GetValue()}

		//发送和接收的操作并不需要一一对应
		err = stream.Send(reply) //生成返回的数据通过流发送给客户端，双向流数据的发送和接收都是完全独立的行为
		if err != nil {
			return err
		}
	}
}

func main() {
	grpcServer := grpc.NewServer()
	pb.RegisterHelloServiceServer(grpcServer, new(HelloServiceImpl))

	lis, err := net.Listen("tcp", ":1234")
	if err != nil {
		log.Fatal(err)
	}
	grpcServer.Serve(lis)
}
